﻿using EMoney.IStock.Client.DataAccess.MC;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models;
using EMoney.IStock.Client.Models.MC;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Linq.Dynamic;
using ThinkDev.Logging;

namespace EMoney.IStock.Client.Business.MC
{
    /// <summary>
    /// 个人信息业务处理类
    /// </summary>
    public class MyInfoBll
    {
        private const string MYINFO_MEMCACHED_KEY = "EMoney.IStock.Client.Business.MC.MyInfoBll.MyInfo";
        private const string USERPIC_MEMCACHED_KEY = "EMoney.IStock.Client.Business.MC.MyInfoBll.UserPic";

        /// <summary>
        /// 获取个人信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public MC_MyInfo GetMyInfo(int userid,bool initTask = false)
        {
            string key = string.Concat(MYINFO_MEMCACHED_KEY, ".", userid);

            MC_MyInfo myInfo = CacheManager.RedisCache.Get<MC_MyInfo>(key);

            if (myInfo == null)
            {
                try
                {
                    bool getUserMessage = false;
                    MyInfoDal myInfoDal = new MyInfoDal();

                    myInfo = myInfoDal.GetMyInfo(userid);

                    if (myInfo == null)
                    {
                        initTask = true;
                        //初始化个人信息
                        myInfo = InitMyInfo(myInfoDal, userid);

                        //获取用户基本信息(用户名、邮箱、手机号)
                        GetUserMessage(myInfo);
                        getUserMessage = true;

                        //初始化完成任务
                        if (initTask)
                        {
                            InitTask(myInfo);
                        }
                    }

                    if (myInfo != null)
                    {
                        if (!getUserMessage)
                        {
                            //获取用户基本信息(用户名、邮箱、手机号)
                            GetUserMessage(myInfo);
                        }

                        //下一级i豆数量
                        myInfo.NextLeveliNum = GetNextLeveliNum(myInfo.Level);

                        TaskInfoDal taskInfoDal = new TaskInfoDal();
                        CompleteTaskRecordDal completeTaskRecordDal = new CompleteTaskRecordDal();

                        DateTime dtNow = DateTime.Now;

                        //已完成的单次任务编号
                        myInfo.CompletedSingleTaskID = taskInfoDal.GetCompletedTaskIDList(myInfo.UserID, MC_TaskType.Single, dtNow);

                        //今日完成的日常任务编号
                        myInfo.CompletedDailyTaskID = taskInfoDal.GetCompletedTaskIDList(myInfo.UserID, MC_TaskType.Daily, dtNow.Date);

                        //今日完成任务记录
                        myInfo.TodayCompleteTaskRecord = completeTaskRecordDal.GetCompleteTaskRecord(myInfo.UserID, dtNow.Date);

                        if (myInfo.TodayCompleteTaskRecord != null && myInfo.TodayCompleteTaskRecord.Count > 0)
                        {
                            myInfo.TaskDate = dtNow.Date;
                        }

                        //连登天数
                        myInfo.ContinueLoginDays = GetContinueLoginDays(myInfo.UserID);

                        CacheManager.RedisCache.Set<MC_MyInfo>(key, myInfo);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "获取个人信息失败");
                }
            }

            if (myInfo != null)
            {
                if (initTask)
                {
                    if (myInfo.TaskDate != DateTime.Now.Date)
                    {
                        if (myInfo.CompletedDailyTaskID != null && myInfo.CompletedDailyTaskID.Count > 0) // || myInfo.TodayCompleteTaskRecord != null
                        {
                            myInfo.CompletedDailyTaskID.Clear();    //清空已完成的日常任务编号
                        }

                        if (myInfo.TodayCompleteTaskRecord != null && myInfo.TodayCompleteTaskRecord.Count > 0)
                        {
                            myInfo.TodayCompleteTaskRecord.Clear(); //清空今日完成任务记录
                        }

                        TaskInfoBll taskInfoBll = new TaskInfoBll();

                        myInfo.ContinueLoginTips = string.Empty;
                        taskInfoBll.CompleteContinueLoginTask(myInfo);  //完成今日登录奖励
                    }
                }

                if (string.IsNullOrEmpty(myInfo.UserPic))
                {
                    GetUserMessage(myInfo);

                    if (string.IsNullOrEmpty(myInfo.UserPic))
                    {
                        myInfo.UserPic = "0";
                    }
                }
            }

            return myInfo;
        }

        /// <summary>
        /// 获取用户连登天数
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        private int GetContinueLoginDays(int userid)
        {
            ContinueLoginDal continueLoginDal = new ContinueLoginDal();

            MC_ContinueLogin continueLogin = continueLoginDal.GetContinueLogin(userid);

            if (continueLogin != null)
            {
                return continueLogin.LoginDays;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 初始化个人信息
        /// </summary>
        /// <param name="myInfoDal"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        private MC_MyInfo InitMyInfo(MyInfoDal myInfoDal,int userid)
        {
            MC_MyInfo myInfo = new MC_MyInfo()
            {
                UserID = userid,
                iNum = 0,
                Level = 0
            };

            if (myInfoDal.AddMyInfo(myInfo) != 1)
            {
                return null;
            }
            else
            {
                return myInfo;
            }
        }

        /// <summary>
        /// 初始化完成任务
        /// </summary>
        /// <param name="myInfo"></param>
        private void InitTask(MC_MyInfo myInfo)
        {
            TaskInfoBll taskInfoBll = new TaskInfoBll();

            //注册成功并登录   taskid:15
            taskInfoBll.CompleteTask(myInfo, 15);

            //验证手机、邮箱   taskid:1            
            if (!string.IsNullOrEmpty(myInfo.Mobile) && !string.IsNullOrEmpty(myInfo.Email))
            {
                taskInfoBll.CompleteTask(myInfo, 1);
            }

            //自选股   taskid:2
            if(!string.IsNullOrEmpty(ClientTokenHelper.GetZxg(myInfo.UserID)))   //存在自选股
            {
                taskInfoBll.CompleteTask(myInfo, 2);
            }

            //持仓股   taskid:3

            //预警     taskid:4
            if (!string.IsNullOrEmpty(ClientTokenHelper.GetAlarmsSetting(myInfo.UserID)))   //存在预警信息
            {
                taskInfoBll.CompleteTask(myInfo, 4);
            }

            //连登任务
            taskInfoBll.CompleteContinueLoginTask(myInfo);
        }

        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="myInfo"></param>
        /// <param name="myInfoDal"></param>
        private void GetUserMessage(MC_MyInfo myInfo)
        {
            string msg = string.Empty;
            MyInfoDal myInfoDal = new MyInfoDal();

            DataTable dtUserMessage = myInfoDal.UserMessage("select", myInfo.UserID, string.Empty, string.Empty, out msg);

            if (dtUserMessage != null && dtUserMessage.Rows.Count > 0)
            {
                myInfo.UserName = dtUserMessage.Rows[0]["username"].ToString();
                myInfo.Mobile = dtUserMessage.Rows[0]["mobile"].ToString();
                myInfo.Email = dtUserMessage.Rows[0]["email"].ToString();
                myInfo.UserPic = dtUserMessage.Rows[0]["userpic"].ToString();
            }
        }

        /// <summary>
        /// 更新用户昵称
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public string UpdateUserName(int userid,string username)
        {
            string msg = string.Empty;
            MyInfoDal myInfoDal = new MyInfoDal();

            try
            {
                myInfoDal.UserMessage("updateusername", userid, username,null, out msg);

                if (string.IsNullOrEmpty(msg))
                {
                    MC_MyInfo myInfo = GetMyInfo(userid);

                    if (myInfo != null)
                    {
                        myInfo.UserName = username;

                        SetMyInfo(myInfo);
                    }

                    return string.Concat("1^",StringHelper.StringSubstrLen(username, 22));
                }
                else
                {
                    return msg;
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, string.Concat("更新用户昵称失败.", userid, ".", username));

                return string.Empty;
            }
        }

        /// <summary>
        /// 更换用户头像
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="userPic"></param>
        /// <returns></returns>
        public string UpdateUserPic(int userid, string userPic)
        {
            string msg = string.Empty;
            MyInfoDal myInfoDal = new MyInfoDal();

            try
            {
                myInfoDal.UserMessage("updatepic", userid, null, userPic, out msg);

                if (string.IsNullOrEmpty(msg))
                {
                    MC_MyInfo myInfo = GetMyInfo(userid);

                    if (myInfo != null)
                    {
                        myInfo.UserPic = userPic;

                        SetMyInfo(myInfo);
                    }

                    return "1";
                }
                else
                {
                    return msg;
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, string.Concat("更换用户头像失败.", userid, ".", userPic));

                return string.Empty;
            }
        }

        /// <summary>
        /// 获取下一等级i豆数量
        /// </summary>
        /// <param name="curLevel"></param>
        /// <returns></returns>
        public int GetNextLeveliNum(int curLevel)
        {
            int retINum = 0;
            ILevelInfoBll iLevelInfoBll = new ILevelInfoBll();

            List<MC_ILevelInfo> listLevel = iLevelInfoBll.GetILevelInfoList();

            if (listLevel != null && listLevel.Count > 0)
            {
                MC_ILevelInfo iLevelInfo = new MC_ILevelInfo();

                iLevelInfo = listLevel.Find(lstLevel => lstLevel.LevelID == curLevel + 1);

                if (iLevelInfo != null)
                {
                    retINum = iLevelInfo.INum;
                }
            }

            return retINum;
        }

        /// <summary>
        /// 设置个人信息缓存
        /// </summary>
        /// <param name="myInfo"></param>
        public void SetMyInfo(MC_MyInfo myInfo)
        {
            if (myInfo != null)
            {
                string key = string.Concat(MYINFO_MEMCACHED_KEY, ".", myInfo.UserID);

                CacheManager.RedisCache.Set<MC_MyInfo>(key, myInfo);
            }
        }

        /// <summary>
        /// 判断 验证手机、邮箱 任务是否完成
        /// </summary>
        /// <param name="userid"></param>
        private void CheckBindTask(int userid,string account,string type)
        {
            MC_MyInfo myInfo = GetMyInfo(userid);

            if (myInfo != null)
            {
                switch (type)
                {
                    case "0":
                        myInfo.Mobile = StringHelper.FormatMobile(account);
                        break;
                    case "1":
                        myInfo.Email = account;
                        break;
                    default:
                        break;
                }

                SetMyInfo(myInfo);
                //GetUserMessage(myInfo);

                if (!string.IsNullOrEmpty(myInfo.Mobile) && !string.IsNullOrEmpty(myInfo.Email))
                {
                    TaskInfoBll taskInfoBll = new TaskInfoBll();

                    taskInfoBll.CompleteTask(myInfo, 1);
                }
            }
        }

        /// <summary>
        /// 绑定账号
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="account"></param>
        /// <param name="type"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public string BindMapUser(int userid,string account,string type,string pwd)
        {
            string ret = string.Empty;
            string pwdMD5 = string.Empty;

            if (pwd != "0")
            {
                pwdMD5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5").ToLower();
            }
            else
            {
                pwdMD5 = "0";
            }

            string url = string.Concat(ConfigHelper.WebAPIUrl, "/User/api/IStock.BindMapUserNew?appid=10001&account=",
                userid, "&toaccount=", account, "&type=", type, "&password=", pwdMD5, "&openid=");

            try
            {
                url = WebApiHelper.CreateUrl(url);

                string result = WebApiHelper.getUrl(url);

                if (!string.IsNullOrEmpty(result))
                {
                    WebApiJson jsonObj = JsonHelper.ToObject<WebApiJson>(result);

                    if (jsonObj != null)
                    {
                        switch (jsonObj.RetCode)
                        {
                            case "1":
                                CheckBindTask(userid,account,type);  //判断 验证手机、邮箱 任务是否完成

                                ret = "1";
                                break;
                            case "-104200001":
                                switch (type)
                                {
                                    case "1":
                                        ret = "邮箱已存在";
                                        break;
                                    default:
                                        ret = "手机号码已存在";
                                        break;
                                }
                                break;
                            default:
                                if (jsonObj.RetMsg.IndexOf("|") > 1)
                                {
                                    ret = jsonObj.RetMsg.Split('|')[1];
                                }
                                else
                                {
                                    ret = jsonObj.Message;
                                }
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, string.Concat("绑定账号失败.", userid, ".", account, ".", type, ".", pwd));
            }

            return ret;
        }

        /// <summary>
        /// 获取头像地址
        /// </summary>
        /// <param name="size"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetUserPic(int size, string name)
        {
            UserPic userPic = null;
            List<UserPic> userPicList = GetUserPicList();

            if (userPicList != null && userPicList.Count > 0)
            {
                userPic = userPicList.Find(lst => lst.Size == size && lst.Name == name);
            }

            if (userPic != null)
            {
                return userPic.Url;
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取用户头像列表
        /// </summary>
        /// <returns></returns>
        public List<UserPic> GetUserPicList()
        {
            try
            {
                List<UserPic> userPicList = CacheManager.DefaultCache.Get<List<UserPic>>(USERPIC_MEMCACHED_KEY);

                if (userPicList == null || userPicList.Count == 0)
                {
                    userPicList = new List<UserPic>();

                    int[] arrSize = new int[] { 25, 32, 77 };

                    foreach (int size in arrSize)
                    {
                        string url = string.Empty;
                        string[] arrDefaultPic = new string[] { "0", "1", "2", "3" };

                        foreach (string defaultPic in arrDefaultPic)
                        {
                            url = string.Concat("IStockClientStatic/mc/images/userpic/", size, "/", defaultPic, ".png");
                            userPicList.Add(new UserPic()
                            {
                                Size = size,
                                Name = defaultPic,
                                Url = StringHelper.GetStaticFile(url)
                            });
                        }

                        string[] arrNewPic = new string[] { "101", "102", "103", "104", "105", "106", "201", "202", "203", "204", "205", "107", "108", "109", 
                            "110", "111", "206", "207", "208", "209", "210", "112", "113", "114", "211", "212", "213", "214" };

                        foreach (string newPic in arrNewPic)
                        {
                            url = string.Concat("IStockClientStatic/mc/images/userpic/", size, "/", newPic, ".png");

                            userPicList.Add(new UserPic()
                            {
                                Size = size,
                                Name = newPic,
                                Url = StringHelper.GetStaticFile(url)
                            });
                        }

                        if (userPicList != null && userPicList.Count > 0)
                        {
                            CacheManager.DefaultCache.Set<List<UserPic>>(USERPIC_MEMCACHED_KEY, userPicList);
                        }
                    }
                }

                return userPicList;
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), "获取用户头像列表失败");

                return null;
            }            
        }

        /// <summary>
        /// 新增i豆流水
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="inum"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public bool AddMyFlow(int userid, int inum,string remark)
        {
            bool ret = false;

            try
            {
                int newINum = 0;

                MC_MyInfo myInfo = new MC_MyInfo();
                MC_ILevelInfo iLevelInfo = new MC_ILevelInfo();

                MyInfoBll myInfoBll = new MyInfoBll();
                ILevelInfoBll iLevelInfoBll = new ILevelInfoBll();

                MyInfoDal myInfoDal = new MyInfoDal();
                MyFlowDal myFlowDal = new MyFlowDal();

                myInfo = myInfoBll.GetMyInfo(userid);

                if (myInfo != null)
                {
                    newINum = myInfo.iNum + inum;
                    myInfo.iNum = newINum;

                    iLevelInfo = iLevelInfoBll.GetILevelInfo(newINum);

                    if (iLevelInfo.LevelID != myInfo.Level)
                    {
                        myInfo.NextLeveliNum = myInfoBll.GetNextLeveliNum(iLevelInfo.LevelID);
                    }

                    myInfo.Level = iLevelInfo.LevelID;

                    myFlowDal.AddMyFlow(new MC_MyFlow()
                    {
                        iNum = inum,
                        UserID = userid,
                        Remark = remark
                    });
                    myInfoDal.UpdateMyInfo(myInfo); //更新个人信息
                    myInfoBll.SetMyInfo(myInfo);    //更新个人信息缓存
                }

                ret = true;
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), 
                    string.Concat("新增i豆流水失败，userid：", userid, "，inum：", inum, "，remark：", remark));
            }

            return ret;
        }

        /// <summary>
        /// 获取用户库用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public OneUserInfo GetOneUserInfo(string username)
        {
            OneUserInfo oneUserInfo = null;

            try
            {
                MyInfoDal myInfoDal = new MyInfoDal();

                oneUserInfo = myInfoDal.GetOneUserInfo(username);
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), "获取用户库用户信息失败");
            }

            return oneUserInfo;
        }
    }
}
